package edu.gmu.projects.fireresponder.gui;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.location.LocationListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import edu.gmu.projects.fireresponder.FirstResponder;
import edu.gmu.projects.fireresponder.R;
import edu.gmu.projects.fireresponder.beacon.BeaconService;
import edu.gmu.projects.fireresponder.comm.UdpBroadcastService;
import edu.gmu.projects.fireresponder.environment.Asset;
import edu.gmu.projects.fireresponder.environment.Building;
import edu.gmu.projects.fireresponder.environment.Location;
import edu.gmu.projects.fireresponder.environment.Path;
import edu.gmu.projects.fireresponder.environment.Route;
import edu.gmu.projects.fireresponder.environment.Safespot;
import edu.gmu.projects.fireresponder.fusionengine.FusionEngine;
import edu.gmu.projects.fireresponder.fusionengine.FusionService;
import edu.gmu.projects.fireresponder.missionplanner.SituationEnvironment;
import edu.gmu.projects.fireresponder.notificationhandler.IMapUpdateListener;
import edu.gmu.projects.fireresponder.notificationhandler.NotificationHandlerService;
import edu.gmu.projects.fireresponder.relevancyengine.RelevanceEngine;
import edu.gmu.projects.fireresponder.relevancyengine.RelevanceEngineService;
import edu.gmu.projects.fireresponder.xml.alerts.FirstResponderAlert;

public class SituationMap extends Activity implements IMapUpdateListener,
		LocationListener {
	public static final String ASSET_ID = ".fireresponder.SituationMap.assetId";
	public static final String ASSET_CLASS = ".fireresponder.SituationMap.assetClass";
	public static final String PROB_FIRE = ".fireresponder.SituationMap.probFire";
	public static final String PROB_PEOPLE = ".fireresponder.SituationMap.probPeople";
	public static final String RELEVANCE = ".fireresponder.SituationMap.relevance";
	public static final String FIRE_DISTANCE = ".fireresponder.SituationMap.fireDistance";
	public static final String TIME_TO_ASSET = ".fireresponder.SituationMap.timeToAsset";
	public static final String PROB_FIRE_AT_TIME = ".fireresponder.SituationMap.probFireAtTime";
	public static final String LAT = ".fireresponder.SituationMap.lat";
	public static final String LNG = ".fireresponder.SituationMap.lng";
	public static final String NO_VALUE = ".fireresponder.SituationMap.noValue";

	public static final String[] MISSION_PLAN_FILE = {
			"json/mission-plan-data-1.json", "json/mission-plan-data-2.json" };

	public static final String ARRAYS_COUNT = ".fireresponder.SituationMap.ARRAYS_COUNT";
	public static final String ARRAY_INDEX = ".fireresponder.SituationMap.ARRAY_INDEX";
	public static final String MISSION_PLAN_VALUE = ".fireresponder.SituationMap.MISSION_PLAN_VALUE";
	public static final String CLEAR_MISSION_PLAN = ".fireresponder.SituationMap.CLEAR_MISSION_PLAN";

	private static final String MAP_URL = "file:///android_asset/android-google-maps.html";

	public static final double SITUATION_LAT = 38.829422;
	public static final double SITUATION_LNG = -77.307617;

	private boolean respondersLayerEnabled = false;
	private boolean attachmentsLayerEnabled = false;

	private WebView webView;
	private android.location.Location mostRecentLocation;

	private ProgressDialog progressDialog;
	private static List<ResponderMessage> ResponderMsgs = new ArrayList<ResponderMessage>();

	public static List<ResponderMessage> getResponderMessages() {
		return ResponderMsgs;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.i("SituationMap", "Created SituationMap activity");

		initPrefs();

		setContentView(R.layout.situation_map);
		setupWebView();
		loadUrlWebView("updateMyLatLng()");
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		startServices();
		bindToServices();
	}

	@Override
	public void onStop() {
		super.onStop();

		Log.i("SituationMap", "Stopped SituationMap activity");
	}

	@Override
	protected void onNewIntent(Intent intent) {
		Bundle extras = intent.getExtras();

		if (extras != null) {
			String newMissionPlanValue = extras.getString(MISSION_PLAN_VALUE);

			if (newMissionPlanValue != null) {
				int index = Integer.parseInt(newMissionPlanValue);
				showMissionPlan(MISSION_PLAN_FILE[index]);
			}

			String clearMissionPlan = extras.getString(CLEAR_MISSION_PLAN);

			if (clearMissionPlan != null) {
				clearMissionPlan();
			}
		}

		Log.i("SituationMap", "Called onNewIntent");
	}

	private void showMissionPlan(String fileName) {
		Log.i("SituationMap", "Loading mission plan: " + fileName);

		loadUrlWebView("showMissionPlan('" + fileName + "')");

		try {
			InputStream stream = getAssets().open(fileName);
			progressDialog = ProgressDialog.show(this, "Loading Mission",
					"In progress...");

			new Thread(new LoadPlanRunner(stream)).start();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			progressDialog.dismiss();
		}
	};

	private class LoadPlanRunner implements Runnable {
		InputStream stream;

		public LoadPlanRunner(InputStream stream) {
			this.stream = stream;
		}

		public void run() {
			relevanceService.getRelevanceEngine().loadPlanFromStream(stream);
			handler.sendEmptyMessage(0);
		}

	}

	private void clearAll() {
		relevanceService.getRelevanceEngine().clearAll();
	}

	private void clearMissionPlan() {
		loadUrlWebView("clearMissionPlan()");
		relevanceService.getRelevanceEngine().clearMissionPlan();
	}

	private void initPrefs() {
		PreferenceManager.setDefaultValues(getApplicationContext(),
				R.xml.situation_map_prefrences, false);

		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(getBaseContext());

		String frNamePref = prefs.getString("frNamePref", "Anonymous");
		SituationEnvironment.getSituationEnvironment(this).getSelf().setId(
				frNamePref);

		Log.i("SituationMap", String.format("Name is set to: %s", frNamePref));
	}

	private class SituationMapWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			view.loadUrl(url);
			return true;
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		unbindFromServices();

		Log.i("SituationMap", "SituationMap activity destroyed");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.map_menu, menu);

		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		MenuItem item = menu.findItem(R.id.mission_plan);

		boolean checked = relevanceService.getRelevanceEngine()
				.getMissionPlan().size() != 0;

		item.setChecked(checked);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.situation_map_menu:
			loadUrlWebView("centerAtLatLng(" + SITUATION_LAT + ","
					+ SITUATION_LNG + ")");
			return true;
		case R.id.my_location_menu:
			loadUrlWebView("updateMyLatLng()");
			loadUrlWebView("centerAtMyLatLng()");
			return true;
		case R.id.notification_list_menu:
			startActivity(new Intent(this, NotificationsList.class));
			return true;
		case R.id.settings_menu:
			startActivity(new Intent(this, SituationMapPreferences.class));
			return true;
		case R.id.clear_marker_menu:
			loadUrlWebView("clearLocationMarker()");
			return true;
		case R.id.my_mission_menu:
			startActivity(new Intent(this, MissionPlanPreferenceActivity.class));
			return true;
		case R.id.responder_attachments:
			if (item.isChecked()) {
				item.setChecked(false);
				attachmentsLayerEnabled = false;
				clearAllResponderAttachments();
			} else {
				item.setChecked(true);
				attachmentsLayerEnabled = true;

				for (ResponderMessage rm : ResponderMsgs) {
					dropAttachmentMarker(rm.getLocation(), 0);
				}
			}
			return true;
		case R.id.responder_team:
			if (item.isChecked()) {
				item.setChecked(false);
				respondersLayerEnabled = false;
				clearAllResponderLocations();
			} else {
				item.setChecked(true);
				respondersLayerEnabled = true;

				Collection<FirstResponder> responders = SituationEnvironment
						.getSituationEnvironment().getTeam();

				for (FirstResponder fr : responders) {
					displayResponderLocation(fr);
				}
			}
			return true;
		case R.id.mission_plan:
			if (item.isChecked()) {
				item.setChecked(false);
				clearMissionPlan();
			} else {
				item.setChecked(true);
				SharedPreferences pref = PreferenceManager
						.getDefaultSharedPreferences(getApplicationContext());

				String indexStr = pref.getString(
						SituationMapPreferences.MISSION_PLAN_PREF, "0");

				int index = Integer.parseInt(indexStr);
				showMissionPlan(MISSION_PLAN_FILE[index]);
			}

			return true;
		case R.id.reload_screen:
			clearAll();
			onStop();
			onCreate(getIntent().getExtras());
			return true;
		}

		return super.onOptionsItemSelected(item);
	}

	private void startServices() {
		Intent udpIntent = new Intent(this, UdpBroadcastService.class);
		startService(udpIntent);

		Intent fusionIntent = new Intent(this, FusionService.class);
		startService(fusionIntent);

		Intent relevanceIntent = new Intent(this, RelevanceEngineService.class);
		startService(relevanceIntent);

		Intent notificationIntent = new Intent(this,
				NotificationHandlerService.class);
		startService(notificationIntent);

		Intent beaconIntent = new Intent(this, BeaconService.class);
		startService(beaconIntent);
	}

	private void bindToServices() {
		bindService(new Intent(SituationMap.this,
				NotificationHandlerService.class), notificationConnection,
				BIND_AUTO_CREATE);
		bindService(
				new Intent(SituationMap.this, RelevanceEngineService.class),
				relevanceConnection, BIND_AUTO_CREATE);
		bindService(new Intent(this, BeaconService.class), beaconConnection,
				BIND_AUTO_CREATE);
		bindService(new Intent(this, FusionService.class), fusionConnection,
				BIND_AUTO_CREATE);
	}

	private void unbindFromServices() {
		unbindService(notificationConnection);
		unbindService(relevanceConnection);
		unbindService(beaconConnection);
		unbindService(fusionConnection);
	}

	private RelevanceEngineService relevanceService;

	private ServiceConnection relevanceConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName name, IBinder service) {
			relevanceService = ((RelevanceEngineService.LocalBinder) service)
					.getService();

			Log.i("SituationMap", "Connected to RelevanceEngineService");
		}

		public void onServiceDisconnected(ComponentName name) {
			relevanceService = null;

			Log.i("SituationMap", "Disconnected from RelevanceEngineService");
		}
	};

	private NotificationHandlerService notificationService;

	private ServiceConnection notificationConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName name, IBinder service) {
			notificationService = ((NotificationHandlerService.LocalBinder) service)
					.getService();
			notificationService.getNotificationHandler().addMapListener(
					SituationMap.this);

			Log.i("SituationMap", "Connected to NotificationHandlerService");
		}

		public void onServiceDisconnected(ComponentName name) {
			notificationService.getNotificationHandler().removeMapListener(
					SituationMap.this);
			notificationService = null;

			Log.i("SituationMap",
					"Disconnected from NotificationHandlerService");
		}
	};

	private BeaconService beaconService;

	private ServiceConnection beaconConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder service) {
			beaconService = ((BeaconService.LocalBinder) service).getService();
			beaconService.addListener(SituationMap.this);

			Log.i("SituationMap", "Connected to BeaconService");
		}

		public void onServiceDisconnected(ComponentName arg0) {
			beaconService.removeListener(SituationMap.this);
			beaconService = null;

			Log.i("SituationMap", "Disconnected from BeaconService");
		}
	};

	private FusionService fusionService;

	private ServiceConnection fusionConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName name, IBinder service) {
			fusionService = ((FusionService.LocalBinder) service).getService();

			Log.i("SituationMap", "Connected to FusionService");
		}

		public void onServiceDisconnected(ComponentName name) {
			fusionService = null;

			Log.i("SituationMap", "Disconnected from RelevanceEngineService");
		}
	};

	private void setupWebView() {
		webView = (WebView) findViewById(R.id.webView);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.setWebViewClient(new SituationMapWebViewClient());
		webView.addJavascriptInterface(new JavaScriptInterface(), "android");
		webView.loadUrl(MAP_URL);
	}

	private void loadUrlWebView(String url) {
		//Log.i("SituationMap", "JavaScriptInterface loadUrlWebView: " + url);
		webView = (WebView) findViewById(R.id.webView);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.loadUrl("javascript:" + url);
	}

	private class JavaScriptInterface {
		@SuppressWarnings("unused")
		public double getSituationLat() {
			return SITUATION_LAT;
		}

		@SuppressWarnings("unused")
		public double getSituationLng() {
			return SITUATION_LNG;
		}

		@SuppressWarnings("unused")
		public double getLatitude() {
			if (mostRecentLocation != null) {
				Log.i("SituationMap", "JavaScriptInterface getLatitude: "
						+ mostRecentLocation.getLatitude());
				return mostRecentLocation.getLatitude();
			}

			return 38.82970;
		}

		@SuppressWarnings("unused")
		public double getLongitude() {
			if (mostRecentLocation != null) {
				Log.i("SituationMap", "JavaScriptInterface getLongitude: "
						+ mostRecentLocation.getLongitude());
				return mostRecentLocation.getLongitude();
			}

			return -77.30731;
		}

		@SuppressWarnings("unused")
		public void showAssetDialog(String assetName) {
			Asset asset = relevanceService.getRelevanceEngine()
					.getEnvironmentAssetById(assetName);

			SituationMap.this.showAssetDialog(asset);
		}

		@SuppressWarnings("unused")
		public void showResponderDialog(String assetName) {
			Asset asset = SituationEnvironment.getSituationEnvironment(
					SituationMap.this).findTeamMember(assetName);

			SituationMap.this.showAssetDialog(asset);
		}

		@SuppressWarnings("unused")
		public void showLocationDialog(double lat, double lng) {
			SituationMap.this.showLocationDialog(lat, lng);
		}

		@SuppressWarnings("unused")
		public void toastAssetInfo(String assetName) {
			Asset asset = relevanceService.getRelevanceEngine()
					.getEnvironmentAssetById(assetName);

			SituationMap.this.toastAssetInfo(asset);
		}

		@SuppressWarnings("unused")
		public void toastLocationInfo(double lat, double lng) {
			SituationMap.this.toastLocationInfo(lat, lng);
		}

		@SuppressWarnings("unused")
		public void toastMessage(String message) {
			Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG)
					.show();
		}

		@SuppressWarnings("unused")
		public void LogMessage(String message) {
			Log.i("JavascriptInterface", message);
		}

		@SuppressWarnings("unused")
		public void showResponderMessageDialog(String position) {
			SituationMap.this.showResponderMessageDialog(position);
		}
	}

	public void showResponderMessageDialog(String position) {
		Log.i("SituationMap", "Location of message/s to display " + position);
	}

	private void toastLocationInfo(double lat, double lng) {
		Location location = new Location(lat, lng);
		Asset asset = relevanceService.getRelevanceEngine().getClosestAsset(
				location);

		if (asset instanceof Building) {
			SituationMap.this.toastAssetInfo(asset);
		} else {
			double probFire = fusionService.getFireProbability(location);
			double probPeople = fusionService.getPresenceProbability(location);

			String probFireStr = String.format("Fire Prob: %s", FusionEngine
					.getProbabilityCategoryText(probFire));
			String probPeopleStr = String.format("People Prob: %s",
					FusionEngine.getProbabilityCategoryText(probPeople));

			String message = String.format("Location\n%.4f, %.4f\n\n%s\n%s",
					lat, lng, probFireStr, probPeopleStr);

			Toast.makeText(SituationMap.this, message, Toast.LENGTH_LONG)
					.show();
		}
	}

	private void showLocationDialog(double lat, double lng) {
		Location location = new Location(lat, lng);
		Asset asset = relevanceService.getRelevanceEngine().getClosestAsset(
				location);

		if (asset instanceof Building) {
			SituationMap.this.showAssetDialog(asset);
		} else {
			String assetId = String.format("Location\n%.4f, %.4f", lat, lng);
			double probFire = fusionService.getFireProbability(location);
			double probPeople = fusionService.getPresenceProbability(location);
			double fireDistance = fusionService.getFireDistance(location, 0.2);

			Bundle bundle = new Bundle();

			// Info that does not fit, fill in to not break things
			bundle.putString(ASSET_CLASS, NO_VALUE);
			bundle.putInt(TIME_TO_ASSET, 0);
			bundle.putDouble(PROB_FIRE_AT_TIME, 0);

			// All good
			bundle.putString(ASSET_ID, assetId);
			bundle.putDouble(PROB_FIRE, probFire);
			bundle.putDouble(PROB_PEOPLE, probPeople);
			bundle.putDouble(RELEVANCE, 0);
			bundle.putDouble(FIRE_DISTANCE, fireDistance);
			bundle.putDouble(LAT, lat);
			bundle.putDouble(LNG, lng);

			startActivity(new Intent(SituationMap.this,
					AssetDialogTabWidget.class).putExtras(bundle));
		}
	}

	private void showAssetDialog(Asset asset) {
		double fireDistance = fusionService.getFireDistance(asset, 0.2);
		int timeToAsset = relevanceService.getRelevanceEngine()
				.estimatedTimeToAsset(asset);
		double probFireAtTime = fusionService.getFireProbability(asset,
				timeToAsset * 1000);

		Bundle bundle = new Bundle();
		bundle.putString(ASSET_ID, asset.getId());
		bundle.putString(ASSET_CLASS, asset.getClass().getName());
		bundle.putDouble(PROB_FIRE, asset.getProbabilityOfFire());
		bundle.putDouble(PROB_PEOPLE, asset.getProbabilityOfPresence());
		bundle.putDouble(RELEVANCE, asset.getRelevanceValue());
		bundle.putDouble(FIRE_DISTANCE, fireDistance);
		bundle.putInt(TIME_TO_ASSET, timeToAsset);
		bundle.putDouble(PROB_FIRE_AT_TIME, probFireAtTime);
		bundle.putDouble(LAT, asset.getCenter().getLatitude());
		bundle.putDouble(LNG, asset.getCenter().getLongitude());

		startActivity(new Intent(SituationMap.this, AssetDialogTabWidget.class)
				.putExtras(bundle));
	}

	private void toastAssetInfo(Asset asset) {
		double probFire = asset.getProbabilityOfFire();
		double probPeople = asset.getProbabilityOfPresence();
		double relevance = asset.getRelevanceValue();

		String assetStr = null;

		if (asset instanceof Path || asset instanceof Safespot) {
			assetStr = String.format("%s %s", asset.getClass().getSimpleName(),
					asset.getId());
		} else {
			assetStr = asset.getId();
		}

		String probFireStr = String.format("Fire Prob: %s", FusionEngine
				.getProbabilityCategoryText(probFire));
		String probPeopleStr = String.format("People Prob: %s", FusionEngine
				.getProbabilityCategoryText(probPeople));
		String relevanceStr = String.format("Mission Relevance: %s",
				RelevanceEngine.getRelevanceScaleText(relevance));

		String message = String.format("%s\n%s\n%s\n%s", assetStr, probFireStr,
				probPeopleStr, relevanceStr);
		Toast.makeText(SituationMap.this, message, Toast.LENGTH_LONG).show();
	}

	private int pickIconByProbability(double fireProb) {
		if (fireProb > .8) {
			return 2;
		}

		if (fireProb > .4) {
			return 1;
		}

		return 0;
	}

	public void displayBuildingOnFire(Building asset) {
		int iconIndex = pickIconByProbability(asset.getProbabilityOfFire());
		String url = String.format("displayBuildingOnFire('%s',%d)", asset
				.getId(), iconIndex);
		loadUrlWebView(url);
	}

	public void displayPathOnFire(Path asset) {
		int iconIndex = pickIconByProbability(asset.getProbabilityOfFire());
		String url = String.format("displayPathOnFire('%s',%d)", asset.getId(),
				iconIndex);
		loadUrlWebView(url);
	}

	public void displayResponderLocation(FirstResponder asset) {
		if (respondersLayerEnabled == true) {
			String url = String.format("displayResponderLocation('%s',%f,%f)",
					asset.getId(), asset.getLocation().getLatitude(), asset
							.getLocation().getLongitude());

			loadUrlWebView(url);
		}
	}

	public void clearAllResponderLocations() {
		loadUrlWebView("clearAllResponderLocations()");
	}

	public void displaySafespotOnFire(Safespot asset) {
		int iconIndex = pickIconByProbability(asset.getProbabilityOfFire());
		String url = String.format("displaySafespotOnFire('%s',%d)", asset
				.getId(), iconIndex);
		loadUrlWebView(url);
	}

	public void displayBuildingDropped(Building asset) {
		String url = String.format("displayBuildingDropped('%s')", asset
				.getId());
		loadUrlWebView(url);
	}

	public void displayTeamMemberBuildingDropped(Building asset) {
		String url = String
				.format("displayBuildingDropped('%s'", asset.getId());
		loadUrlWebView(url);
	}

	public void displayBuildingCleared(Building asset) {
		String url = String.format("displayBuildingCleared('%s')", asset
				.getId());
		loadUrlWebView(url);
	}

	public void displayRouteOnFire(Route asset) {
		loadUrlWebView("displayRouteOnFire()");
	}

	public void displayPeopleInBuilding(Asset asset) {
		String url = String.format("displayPeopleInBuilding('%s')", asset
				.getId());
		loadUrlWebView(url);
	}

	public void removePeopleInBuildingDisplay(Building asset) {
		String url = String.format("removePeopleInBuilding('%s')", asset
				.getId());
		loadUrlWebView(url);
	}

	public void onLocationChanged(android.location.Location location) {
		Log.i("SituationMap", "onLocationChanged");

		this.mostRecentLocation = location;
		loadUrlWebView("updateMyLatLng()");
	}

	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	public void clearAllResponderAttachments() {
		loadUrlWebView("clearAllResponderAttachments()");
	}

	// Precondition: alert has either message, or image, or both
	public void displayResponderAttachments(FirstResponderAlert alert) {
		boolean hasMessage = false;
		boolean hasImage = false;

		ResponderMessage responderMsg = null;

		if (alert.getMessage() != null && alert.getMessage().length() > 0) {
			responderMsg = new ResponderMessage(alert);
			ResponderMsgs.add(responderMsg);
			hasMessage = true;
		}

		if (alert.getImageContents() != null
				&& alert.getImageContents().length > 0) {

			FileUtilities.saveImage("images/frapp/"
					+ FileUtilities.santitizeToFileName(alert.getLocation()
							.toString()), alert.getImageContents());

			hasImage = true;
		}

		int typeId = hasMessage && hasImage ? 2 : hasMessage ? 0 : 1;
		dropAttachmentMarker(alert.getLocation(), typeId);
	}

	private void dropAttachmentMarker(Location location, int typeId) {
		Asset asset = relevanceService.getRelevanceEngine().getClosestAsset(
				location);

		String url = null;

		if (relevanceService.getRelevanceEngine().isAssetInMission(asset)) {
			if (asset instanceof Building) {
				url = String.format("displayAttachmentOnBuilding('%s')", asset
						.getId());
			} else {
				double lat = asset.getCenter().getLatitude();
				double lng = asset.getCenter().getLongitude();

				url = String.format("displayAttachmentOnLocation(%d, %f, %f)",
						typeId, lat, lng);
			}
		} else if (attachmentsLayerEnabled) {
			double lat = location.getLatitude();
			double lng = location.getLongitude();

			url = String.format("displayAttachmentOnLocation(%d,%f,%f)",
					typeId, lat, lng);
		}

		if (url != null) {
			loadUrlWebView(url);
		}
	}

	public void loadNewMissionPlan(String plan) {
		String url = String.format("loadNewPlanFromString('%s')", plan);
		loadUrlWebView(url);
	}

	public void loadedNewMissionPlan() {
		//progressDialog = ProgressDialog.show(this, "Loading New Mission", "In progress...");
	}

	public void loadingNewMissionPlan() {
		//progressDialog.dismiss();
	}

	public void updateMostRelevantAsset(Asset asset) {
		String url = String.format("updateMostRelevantAsset('%s')", asset.getId());
		loadUrlWebView(url);
	}
}